class Solution {
private:
    TreeNode* ans = nullptr;
public:
    bool dfs(TreeNode* root, TreeNode* p, TreeNode* q)
    {
        if (root == nullptr) {
            return false;
        }
        bool l = dfs(root->left, p, q);
        bool r = dfs(root->right, p, q);
        if ((l && r) || ((root->val == p->val || root->val == q->val) && (l || r))) {
            ans = root;
        }
        return (root->val == p->val) || (root->val == q->val) || (l || r);
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {
        dfs(root, p, q);
        return ans;
    }
};